<template>
  <!-- 商品信息 -->
  <div class="component-take-stock-sku-info prodItem-container">
    <span class="title">{{ $t('group.prodInfo') }}</span>
    <el-divider />
    <div
      v-if="isAuth('multishop:takeStockProd:select')"
      class="default-btn primary-btn"
      @click="selectSupplierProd()"
    >
      {{ $t('shop.addProd') }}
    </div>
    <el-tooltip
      class="item"
      :disabled="takeStockProdItems.length === 0"
      effect="dark"
      :content="$t('takeStock.importErrorTip')"
      placement="top"
    >
      <div
        class="default-btn"
        :class="{'disabled-btn': takeStockProdItems.length > 0}"
        @click="uploadSku"
      >
        {{ $t('stock.batchImport') }}
      </div>
    </el-tooltip>
    <div class="count-desc-text">
      {{ $t('takeStock.infoText1') }}{{ takeStockProdItems.length }}{{ $t('takeStock.infoText2') }}{{ totalStock }}{{ $t('takeStock.infoText3') }}{{ profitCount }}{{ $t('takeStock.infoText4') }}{{ lossCount }}{{ $t('takeStock.infoText5') }}
    </div>
    <div class="prodItem-table">
      <!-- 状态导航选择组件 -->
      <statusSelectTabs
        :status-arr="statusArr"
        :default-key="statusArr[0].key"
        @status-change="statusChange"
      />
      <el-table
        :data="totalList.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize)"
        header-cell-class-name="table-header"
        row-class-name="table-row"
      >
        <el-table-column
          :label="$t('group.prodInfo')"
          fixed="left"
          align="center"
          width="320px"
        >
          <template #default="scope">
            <div class="prod-info">
              <ImgShow
                :src="scope.row.pic"
                :img-style="{width:'60px',height:'60px'}"
              />
              <div class="text">
                <span class="name">{{ scope.row.prodName }}</span>
                <span class="name">{{ scope.row.skuName }}</span>
                <span class="name">{{ scope.row.partyCode }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="bookStock"
          :label="$t('takeStock.bookStock')"
          align="center"
        >
          <template #default="scope">
            <span class="table-cell-text line-clamp-one">{{ scope.row.stocks }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="stock_count"
          align="center"
        >
          <template #header>
            {{ $t('takeStock.profitLossCount') }}
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('takeStock.profitLossTip')"
              placement="top"
            >
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">
            <span class="table-cell-text line-clamp-one">{{ scope.row.changeStock > 0 ? '+'+scope.row.changeStock : scope.row.changeStock }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('takeStock.totalStock')"
          prop="totalStock"
          align="left"
        >
          <template #default="scope">
            <el-input
              v-model.number="scope.row.totalStock"
              type="number"
              style="maxWidth: 150px"
              oninput="if(value<0 || value >1000000000)value=0"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              @keydown="channelInputLimit"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publics.remark')"
          prop="remark"
          align="left"
          min-width="150"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.remark"

              style="maxWidth: 150px"
              show-word-limit
              maxlength="20"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('crud.menu')"
          fixed="right"
        >
          <template #default="scope">
            <div class="text-btn-con">
              <div
                class="default-btn text-btn"
                @click="onDelete(scope.row.skuId,totalList.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize))"
              >
                {{ $t('text.delBtn') }}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page.currentPage"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalList.length"
        @current-change="onPageChange"
      />
    </div>
    <!-- 供应商商品选择弹窗-->
    <supplier-prod-select
      v-if="supplierProdSelectVisible"
      ref="supplierProdSelectRef"
      @refresh-select-supplier="supplierProdSelectHandle"
    />
    <takeStockProdUpload
      v-if="batchImportVisible"
      ref="takeStockProdUploadRef"
      @refresh-data-list="refreshDataList"
    />
  </div>
</template>

<script setup>
import statusSelectTabs from '../../components/status-select-tabs.vue'
import takeStockProdUpload from './take-stock-prod-upload.vue'
import { isAuth } from '@/utils'
const props = defineProps({
  // eslint-disable-next-line vue/require-prop-types
  takeStockId: {
    default: 0
  }
})

//
// eslint-disable-next-line vue/no-setup-props-destructure
let _takeStockId = props.takeStockId

const takeStockProdItems = ref([]) // 已选择的商品项
const supplierProdSelectVisible = ref(false)
const batchImportVisible = ref(false) // 批量导入商品弹窗是否可见

// eslint-disable-next-line no-unused-vars
let verifyFlag = true // 数据校验标记，true：正确，false：错误
const totalStock = ref(0) // 实盘库存
const profitCount = ref(0) // 盘盈
const lossCount = ref(0) // 盘亏
let profitProdList = [] // 盘盈列表
let lossProdList = [] // 盘亏列表
let equalProdList = [] // 盘平列表
const totalList = ref([])
const statusArr = [
  { id: 0, key: null, label: $t('stock.all') },
  { id: 1, key: 1, label: $t('takeStock.profit') },
  { id: 2, key: 2, label: $t('takeStock.loss') },
  { id: 3, key: 0, label: $t('takeStock.equal') }
] // 状态导航组件参数
const page = reactive({
  currentPage: 1, // 初始页
  pageSize: 10 // 每页数据大小
})
const tab = {
  key: ''
}
watch(() => takeStockProdItems.value, (val) => {
  countChange(val)
}, {
  deep: true
})

onMounted(() => {
  init()
})

const init = () => {
  _takeStockId = Number(_takeStockId)
  if (_takeStockId) {
    getSkuList()
  }
}
const getSkuList = () => {
  http({
    url: http.adornUrl('/stock/takeStockProd/list'),
    method: 'get',
    params: http.adornParams(
      {
        takeStockId: _takeStockId
      }
    )
  }).then(({ data }) => {
    takeStockProdItems.value = data
    statusChange(statusArr[0])
    countChange(takeStockProdItems.value)
  })
}
/**
 * 导航选择状态
 */
const statusChange = (item) => {
  totalList.value = []
  switch (item.key) {
    case 1: totalList.value = profitProdList
      break
    case 2: totalList.value = lossProdList
      break
    case 0: totalList.value = equalProdList
      break
    default: totalList.value = takeStockProdItems.value
      break
  }
  page.currentPage = 1
  tab.key = item.key
}
const countChange = (newValue) => {
  profitProdList = []
  lossProdList = []
  equalProdList = []
  let _totalStock = 0
  let _profitCount = 0
  let _lossCount = 0
  newValue.forEach(item => {
    if (!item.totalStock && item.totalStock !== 0) {
      item.totalStock = null
    }
    item.takeStockId = _takeStockId
    item.changeStock = item.totalStock - item.stocks
    _totalStock += item.totalStock
    if (item.stocks > item.totalStock) {
      _lossCount += item.stocks - item.totalStock
      lossProdList.push(item)
    } else if (item.stocks < item.totalStock) {
      _profitCount += item.totalStock - item.stocks
      profitProdList.push(item)
    } else if (item.stocks === parseInt(item.totalStock) || (item.stocks === 0 && !item.totalStock)) {
      equalProdList.push(item)
    }
  })
  totalStock.value = Number(_totalStock)
  profitCount.value = Number(_profitCount)
  lossCount.value = Number(_lossCount)
}
// 选择商品
const supplierProdSelectRef = ref(null)
const selectSupplierProd = () => {
  const ids = []
  takeStockProdItems.value.forEach(item => {
    ids.push(item.skuId)
  })
  const data = {
    skuIds: ids
  }
  supplierProdSelectVisible.value = true
  nextTick(() => {
    supplierProdSelectRef.value?.init(data)
  })
}
// 商品选择回调
const supplierProdSelectHandle = (prodItem) => {
  prodItem.forEach(prod => {
    if (!takeStockProdItems.value.find(el => el.skuId === prod.skuId)) {
      takeStockProdItems.value.push(prod)
    }
  })
  totalList.value = takeStockProdItems.value
  verifyFlag = totalList.value.length !== 0
}
const takeStockProdUploadRef = ref(null)
const uploadSku = () => {
  if (takeStockProdItems.value.length > 0) {
    return
  }
  batchImportVisible.value = true
  nextTick(() => {
    takeStockProdUploadRef.value?.init(_takeStockId)
  })
}
const refreshDataList = () => {
  getSkuList()
}
/**
 * 校验数据，校验成功返回数据项，不成功返回null
 */
const verifyDataForm = () => {
  if (takeStockProdItems.value.length === 0) {
    verifyFlag = false
    return null
  } else {
    verifyFlag = true
    return takeStockProdItems.value
  }
}
/**
 * 删除已选择的商品项
 * @param skuId 当前商品项在当前页的位置
 * @param list 当前列表
 */
const onDelete = (skuId, list) => {
  let index = 0
  for (let i = 0; i < takeStockProdItems.value.length; i++) {
    if (takeStockProdItems.value[i].skuId === skuId) {
      index = i
      break
    }
  }
  takeStockProdItems.value.splice(index, 1)
  // 判断当前页码是否超过删除后的页码大小
  if (page.currentPage > ((takeStockProdItems.value.length - 1) / page.pageSize + 1)) {
    page.currentPage = --page.currentPage || 1
  }
  countChange(takeStockProdItems.value)
  statusChange(tab)
}
const onPageChange = (val) => {
  page.currentPage = val
}
const channelInputLimit = (e) => {
  const key = e.key
  if (key === '.') {
    e.returnValue = false
    return false
  }
  return true
}

defineExpose({
  verifyDataForm,
  getSkuList
})
</script>

<style lang="scss" scoped>

.prodItem-container {
  .title {
    color: #333333;
    font-size: 16px;
    font-weight: bold;
  }

  .count-desc-text {
    margin-top: 8px;
    margin-bottom: 8px;
    color: #333333;
    font-size: 14px;
  }

  .disabled-btn {
    color: #C0C4CC;

    &:hover {
      cursor: not-allowed;
      color: #C0C4CC;
    }
  }

  .prodItem-table {
    .prod-info {
      display: flex;
      align-items: center;
    }

    .prod-info .text {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      margin-left: 10px;
      width: 170px;
    }

    .prod-info .text .name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: left;

    }
  }
}
@media (max-width: 1440px) {
  :deep(.el-card__body) {
    padding-bottom: 40px !important;
  }
}
</style>
